'''
Created on Apr 23, 2013

@author: wdoering
'''
import os
import urllib2
import glob, ListFile, datetime
class CacheProxy(object): 
    
    
    def __init__(self, cacheLabel, cacheSize = 1048576, lockTimeout = 600):
        self.cacheSize = cacheSize
        self.cacheLabel = cacheLabel
        self.cacheList = list()
        self.lockTimeout = lockTimeout
        #print "init!"
    
    def isPageInCache(self, url):
        
        fileFullName = url.split('//')[1]
        fileFullName = fileFullName.replace('.', '_')
        fileName = fileFullName.replace(':', '_')
        fileName = fileName + ".html"
        
        startPath = 'cache/'
        for dirpath, dirnames, filenames in os.walk(startPath):
            for f in filenames:
                #print f
                if f == fileName:
                    return True
        return False
        
    def getFile(self,websiteUrl):  
            url = websiteUrl
            
            file_full_name = url.split('//')[1]
            file_full_name = file_full_name.replace('.', '_')
            file_full_name = file_full_name.replace('/', '-')
            file_name = file_full_name.replace(':', '_')
            file_path = "cache/" + file_name + ".html"
            
            u = urllib2.urlopen(url)
            try:
                f = open(file_path, 'wb')
                
                meta = str(u.info())
                f.write(meta)
                headers = u.info().headers
                #file_size = int(meta.getheaders("Content-Length")[0])
                #print "Downloading: %s Bytes: %s" % (file_name, file_size)
                
                file_size_dl = 0
                block_sz = 8192
                while True:
                    bufferer = u.read(block_sz)
                    if not bufferer:
                        break
                
                    file_size_dl += len(bufferer)
                    f.write(bufferer)
                
                f.close()
            except IOError:
                return False
            timestamp = datetime.datetime.now()
            self.cacheList.append(ListFile.ListFile(timestamp, file_path, self.lockTimeout))
            currentCache = int(self.getSize())
            #print (str(currentCache) + ' - currentCache ' + str(self.cacheSize) + ' - cacheSize')
            if currentCache >= int(self.cacheSize):
                self.delete(file_path)
                #self.deleteLRU() :(
            d = self.getSize()
            self.cacheLabel.set("Cache usage : "+str(d))
    def getFileFromCache(self, url):
        file_full_name = url.split('//')[1]
        file_full_name = file_full_name.replace('.', '_')
        file_full_name = file_full_name.replace('/', '-')
        file_name = file_full_name.replace(':', '_')
        file_path = "cache/" + file_name + ".html"
        
        if not self.isPageInCache(url):
            return False
        for i in self.cacheList:
            name = i.getFileName
            if file_name == name:
                i.lock()
                i.setTimestamp(datetime.datetime.now())
            
        f = open(file_path, 'wb')
        return f.read()
    
    def unlockFile(self, url):
        file_full_name = url.split('//')[1]
        file_full_name = file_full_name.replace('.', '_')
        file_full_name = file_full_name.replace('/', '-')
        file_name = file_full_name.replace(':', '_')
        
        if not self.isPageInCache(url):
            return False
        for i in self.cacheList:
            name = i.getFileName
            if file_name == name:
                i.unlock()
                
    def getSize(self):
        start_path = "cache/"
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                total_size += os.path.getsize(fp)
        return total_size
    
    def deleteFile(self, fileName):
        print 'deleteFile: '+fileName
        filelist = glob.glob(fileName)
        for f in filelist:
            print 'deleting '+fileName
            os.remove(f)
    
    def deleteLRU(self):
        count = 0
        least = ''
        while 1:
            if self.cacheList[count].isPresent():
                least = self.cacheList[count]
                break
            count += 1
        
        for i in self.cacheList:
            if i.isUnlocked() and i.isPresent() and i.getTimestamp() < least.getTimestamp():
                least = i
        self.deleteFile(least.getFileName())
        least.notPresent()
        currentCache = int(self.getSize())
        if currentCache >= int(self.cacheSize):
                self.deleteLRU()
    def kill(self):
        print 'kill'
        filelist = os.listdir('cache')
        for f in filelist:
            os.remove('cache/'+f)
        #shutil.rmtree('/home/alex/Development/aptana_workspace/CMSC506 Web Proxy/src/cache/')
    
    '''        
    def checkFilesTimestamp(self, start_path = "cache/"):
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                oldestFile = time.time()
                timestamp = time.ctime(os.path.getmtime(start_path + f))
                if timestamp > oldestFile:
                    oldestFile = timestamp
                    
        return oldestFile        
    '''
